from flask import Blueprint, render_template, jsonify, redirect, url_for, session
from exts import db
from flask import request
from models import UserModel
from .form import RegisterForm,LoginForm
from werkzeug.security import generate_password_hash, check_password_hash


bp = Blueprint("auth", __name__, url_prefix="/auth")

@bp.route("/login", methods=["GET","POST"])
def login():
    if request.method == "GET":
        return render_template("login.html")
    else:
        form = LoginForm(request.form)
        if form.validate():
            email = form.email.data
            password = form.password.data
            user = UserModel.query.filter_by(email=email).first()
            if not user:
                print("邮箱在数据库中不存在")
                return redirect(url_for("auth.register"))
            if check_password_hash(user.password, password):
                #cookie：令牌
                #cookie中不适合存储太多的数据
                #cookie一般用来存放登录授权的东西
                #flask中的session，是经过加密后存储在cookie中
                session["user_id"] = user.id
                return redirect("/")
            else:
                print("密码错误")
                return redirect(url_for("auth.login"))
        else:
            print(form.errors)
            return redirect(url_for("auth.login"))


@bp.route("/logout")
def logout():
    session.clear()
    return redirect("/")



#GET请求：从服务器上获取数据
#POST请求：对客户端的数据提交给服务器端
@bp.route("/register", methods=["GET","POST"])
def register():
    if request.method == "GET":
        return render_template("register.html")
    else:
        #验证用户提交的邮箱和验证码是否对应正确
        #表单验证：flask-wtforms
        form = RegisterForm(request.form)
        if form.validate():
            email = form.email.data
            username = form.username.data
            password = form.password.data
            user = UserModel(email=email, username=username, password=generate_password_hash(password))
            db.session.add(user)
            db.session.commit()
            return redirect(url_for("auth.login"))
        else:
            print(form.errors)
            return render_template("register.html", form=form)






